import {
    run,
    queryAll,
    queryOne,
    queryCount,
    insert,
    insertOrReplace,
    insertOrIgnore,
    update
} from '../ADB'

// userId从store中获取
import store from '../../store'
import { startServer } from '../../file';
const os = require('os');
const userDir = os.homedir();  // 获取用户目录 C:\Users\用户名

/* 增加未处理的申请信息数量 */
const updateContactNoReadCount = (increaseCount) => {
    return new Promise(async (resolve, reject) => {
        try {
            if (increaseCount != null) {
                let sql = `update user_setting set contact_no_read = contact_no_read + ? where user_id = ?`
                await run(sql, [increaseCount, store.getUserId()])
                resolve();
            } else {
                // 传递null就清空未读数量
                let sql = `update user_setting set contact_no_read = 0 where user_id = ?`
                await run(sql, [store.getUserId()])
                resolve();
            }
        } catch (e) {
            console.error("updateContactNoReadCount error: " + e)
            resolve();  // 忽略错误
        }
    })
}

/* 保存用户设置 */
const saveUserSetting = async (userSetting) => {
    // user_id, email, sys_setting, contact_no_read, server_port
    // 端口不能冲突，先查出最大的端口号，然后+1
    let sql = `select max(server_port) serverPort from user_setting`
    let { serverPort } = await queryOne(sql)
    if (serverPort == null) serverPort = 10240;
    else serverPort++;
    // 默认文件存储路径
    const sysSetting = {
        fileFolder: userDir + '\\.r-chat-data\\fileStorage\\' + userSetting.userId,
    }
    let fileFolder = sysSetting.fileFolder;
    // 查找是否有该用户，有则获取信息，没有则插入
    sql = `select * from user_setting where user_id = ?`
    const userInfo = await queryOne(sql, userSetting.userId)
    if (userInfo) {
        serverPort = userInfo.serverPort;
        fileFolder = JSON.parse(userInfo.sysSetting).fileFolder;
    }
    else {
        // 插入数据
        await insertOrIgnore('user_setting', {
            userId: userSetting.userId,
            email: userSetting.email,
            sysSetting: JSON.stringify(sysSetting),
            contactNoRead: 0,
            serverPort: serverPort
        })
    }
    // 将信息存入store，方便获取
    store.setUserData("fileFolder", fileFolder);
    store.setUserData("serverPort", serverPort);
    // 启动本地服务，用于获取文件
    startServer(serverPort);
}

/* 获取用户设置信息 */
const getUserSetting = () => {
    let sql = `select * from user_setting where user_id = ?`
    return queryOne(sql, store.getUserId())
}

/* 更新系统设置信息 */
const updateSysSetting = (sysSetting) => {
    return update('user_setting', { sysSetting: JSON.stringify(sysSetting) }, { userId: store.getUserId() })
}

/* 获取本地数据库中的所有登陆过的邮箱信息 */
const getUserEmailList = () => {
    return queryAll(`select email from user_setting where email is not null`)
}

export {
    updateContactNoReadCount,
    saveUserSetting,
    getUserSetting,
    updateSysSetting,
    getUserEmailList
}